package org.xydpeng.framework.l2cache.serialization;

import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

/**
 * @author xydpeng
 * @version v1.0
 * @date: 2024/6/13
 * @description:
 */
public class DelegatedRedisSerializer implements RedisSerializer {
    public static final byte[] EMPTY_ARRAY = new byte[0];

    protected final Serialization serialization;

    public DelegatedRedisSerializer(Serialization serialization) {
        this.serialization = serialization;
    }

    @Override
    public byte[] serialize(Object value) throws SerializationException {
        if (value == null) {
            return EMPTY_ARRAY;
        }
        try {
            return this.serialization.serialize(value);
        } catch (Exception ex) {
            throw new SerializationException("Could not write JSON: " + ex.getMessage(), ex);
        }
    }

    @Override
    public Object deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        try {
            return this.serialization.deserialize(bytes);
        } catch (Exception ex) {
            throw new SerializationException("Could not read JSON: " + ex.getMessage(), ex);
        }
    }
}
